package com.tanhua.manager.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.manager.service.PaperService;
import com.tanhua.pojo.Paper;
import com.tanhua.service.PicUploadService;
import com.tanhua.vo.PicUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/paper")
public class PaperController {

    @Autowired
    private PaperService paperService;

    @Autowired
    private PicUploadService picUploadService;

    @PostMapping
    public Boolean insertOne(@RequestBody Paper paper) {
        return paperService.insertOne(paper);
    }

    @GetMapping("/{pageNum}/{pageSize}")
    public IPage<Paper> findByPage(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        System.out.println(paperService.findByPage(pageNum, pageSize).getRecords());
        return paperService.findByPage(pageNum, pageSize);
    }

    @PutMapping
    public Boolean update(@RequestBody Paper paper) {
        System.out.println(paper);
        return paperService.updateById(paper);
    }

    @DeleteMapping("/{paperId}")
    public Boolean delete(@PathVariable("paperId") Integer paperId) {
        System.out.println(paperId);
        return paperService.removeById(paperId);
    }

    @DeleteMapping("/many/{num}")
    public Boolean deleteMany(@PathVariable("num") String num) {
        System.out.println(num);
        return paperService.removeByIds(Arrays.stream(num.split(",")).collect(Collectors.toList()));
    }

    @GetMapping
    private List<Paper> findAll() {
        //System.out.println(paperService.findAll().toString());
        return paperService.findAll();
    }

    @PostMapping("/upload/{paperId}")
    public void uploadFile(List<MultipartFile> file, @PathVariable("paperId") Integer paperId) {
        //System.out.println(paperId);
        //System.out.println(file.get(0));
        PicUploadResult upload = picUploadService.upload(file.get(0));
        Paper paper = paperService.findById(paperId);
        paper.setCover(upload.getName());
        paperService.updateById(paper);
    }
}
